package swingExtended.swingControlGroup;

import com.google.common.base.Function;
import com.google.common.collect.Maps;
import java.util.HashMap;
import java.util.Set;
import java.util.Map;

/**
 *
 * @author Shimu
 * @date 9-Jan-2013
 */
public abstract class BindableControlMap  {

    private final Map<String, BindableControl> MAPPING = new HashMap<>();
    private final Map<String, Object> SNAP_SHOT = new HashMap<>();

    public BindableControlMap() {
    }

    /**
     * Takes a snap shot of the values of all the text fields. Can call the
     * method reset() later to restore all the text fields to their respective
     * value stored during this call to snapShot.
     */
    public void snapShot() {
        SNAP_SHOT.clear();

        SNAP_SHOT.putAll(getMapping());
    }

    /**
     * Resets all the text field to their respective values during the last 
     * snap shot point.
     */
    public void reset() {
        loadFromMapping(SNAP_SHOT);
    }

    /**
     * @param key a unique key that will be used to identify the given
     * JTextField
     * @param value the JTextField to be grouped
     * @throws IllegalArgumentException if the given key contains a special
     * separator value used for storing the text fields to a text file.
     * @return the previous JTextField, null if it did not exist.
     */
    public BindableControl put(String key, BindableControl component) {
        if (component == null) {
            throw new IllegalArgumentException("Component cannot be null!");
        }
        return MAPPING.put(key, component);
    }

    /**
     * Returns the text stored in the JTextField pointed to by the given key.
     * 
     * @param key
     * @throws NullPointerException a JTextField with the given key does not
     * exist
     * @return 
     */
    public Object getValue(String key) {
        return MAPPING.get(key).getBindedValue();
    }

    public void loadFromMapping(Map<String, ?> map) {        
        Set<String> keys = map.keySet();
        for (String k : keys) {
            if (MAPPING.containsKey(k)) {
                MAPPING.get(k).setText(map.get(k));
            }            
        }
    }

    public Map<String, Object> getMapping() {
        return Maps.transformValues(MAPPING, new Function<BindableControl, Object>(){

            @Override
            public Object apply(BindableControl input) {
                return input.getBindedValue();
            }
        }); 
    }
    
    /*
    public void save(String url) throws IOException {
        UnusedIO.save(url, getMapping());
    }*/
}
